package com.sjl.db137.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sjl.db137.config.JwtUtils;
import com.sjl.db137.config.R;
import com.sjl.db137.entity.Menu;
import com.sjl.db137.entity.User;
import com.sjl.db137.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;

/**
 * @Author: zero domain
 * @CreateTime: 2024/12/24 11:50
 * @Description: TODO
 * @Version: 1.0
 */

/**
 * user相关
 */
@CrossOrigin(origins = "*")
@RestController
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 根据当前用户返回用户的菜单集合数据
     * @return
     */
    @GetMapping("/selectUserMenu")
    public Object selectUserMenu(@RequestHeader("token") String token) {
        System.out.println("请求头 " + token);
        //解析token，获取用户信息
        Integer userid = JwtUtils.getJwtToken(token,"userid");
        System.out.println("userid = " + userid);
        //int userid=1;
        List<Menu> menuList = this.userService.selectUserMenuByUserId(userid);
        return new R().add("",menuList);
    }

    @GetMapping("userlogin")
    public User userlogin(String uname, String upwd){
        return this.userService.userlogin(uname,upwd);
    }

    @GetMapping("insertuser")
    public int userinsert(User user){
        System.out.println("user = " + user);
        return this.userService.insertUser(user);
    }

    @RequestMapping("userregister")
    public R register(@RequestBody User user){
        return new R().add("user",this.userService.register(user));
    }

    @PostMapping("userlogin2")
    public R login(@RequestBody User user){
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();//构建一个查询容器
        userQueryWrapper.setEntity(user);
        User u = this.userService.getOne(userQueryWrapper);
        if (u!=null){//登录成功
            //生成token
            HashMap<String, Object> map = new HashMap<>();
//            u.setUpwd("");
//            map.put("user",u);
            map.put("userid",u.getId());
            String jwtToken = JwtUtils.createJwtToken(map);
            System.out.println("jwtToken = " + jwtToken);
            return new R().add("token",jwtToken);
        }
        //登录失败
            return new R().setMsgerr("登录出错").setCode(500);
    }

    /***
     * 获取用户集合
     * @return
     */
    @GetMapping("selectuser")
    public R selectuser(){
        List<User> userList = this.userService.list();
        return new R().add("userList",userList);
    }

}
